package pcvc.teacher;

import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.osoa.sca.annotations.Init;
import org.osoa.sca.annotations.Reference;

import pcvc.common.classes.PCVCAbstractObserver;
import pcvc.common.classes.Question;
import pcvc.common.classes.StudentAnswer;
import pcvc.common.services.IPCVCServerTeacherService;

public class PCVCTeacher extends PCVCAbstractObserver
{
    private static final String ASSIGNMENT_PATTERN = "^\\s*(\\p{Alpha}[\\p{Alnum}_]*)\\s*=([^=].*)$";
    private Map<String, String> variables;

    @Reference(name="serverTeacherService")    
    private IPCVCServerTeacherService service;
    
    private Set<StudentAnswer> answers;
    
    private List<String> comments;
    
    public PCVCTeacher()
    {
        variables = new LinkedHashMap<String, String>( );
    }

    public void update( )
    {
        comments = getComments( );
        answers = getAnswers( );
    }
    
    public void addVariable(String expression)
    {
        Pattern assignmentPattern = Pattern.compile( ASSIGNMENT_PATTERN );
        Matcher assignmentMatcher = assignmentPattern.matcher( expression );
        
        if(assignmentMatcher.find( ))
        {
            String variableName = assignmentMatcher.group( 1 );
            String expr = assignmentMatcher.group(2);
            
            variables.put( variableName, expr );
        }
    }
    
    public void sendQuestion(Question question)
    {
        service.sendQuestion( question );
        answers = new LinkedHashSet<StudentAnswer>( );
    }
    
    private List<String> getComments()
    {
        return service.getComments( );
    }
    
    private Set<StudentAnswer> getAnswers()
    {
        return service.getAnswers( );
    }
    
    @Init
    public void setSubject()
    {
        subject.attach( this );
    }
}